<?php
// 设计师小助手自动回复问题
namespace Frieza\Modules\Autoreply\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Frieza\Modules\Autoreply\Actions\AnswerAdd;
use Frieza\Modules\Autoreply\Actions\QuestionDelete;
use Doraemon\model\Message\AutoReply;
use Doraemon\cache\Designer\AutoReply as cAutoReply;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Encore\Admin\Grid\Displayers\DropdownActions;

class DesignerQuestionController extends Controller {

    const PAGE_SIZE = 20;

    const STATUS_DOT = [
        AutoReply::STATUS_NORMAL => 'success',
        AutoReply::STATUS_HIDDEN => 'info',
        AutoReply::STATUS_DELETE => 'danger'
    ];

    public function index(Request $request, Content $content) {
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $condition['question_id'] = 0;
        $condition['data_status'] = [AutoReply::STATUS_NORMAL, AutoReply::STATUS_HIDDEN];
        $total = AutoReply::count($condition);
        $condition['ORDER'] = ['data_sort' => 'ASC'];
        $lists = AutoReply::select('*', $condition);
        $this->formatList($lists);
        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column('id', '问题ID');
                $grid->column('reply_title', '问题');
                $grid->column('', '自动回复')->display(function() {
                    return $this->reply_cnt;
                })->expand(function() {
                    $replyA = $this->reply_a;
                    if ($replyA) {
                        foreach ($replyA as &$answer) {
                            $answer['reply_link'] = '<a class="fa " href="javascript:layer.open({type: 2,
                    title: \'预览\', maxmin: true, area: [\'650px\', \'700px\'],
                    content: \'' . $answer['reply_link'] . '\' });">' . htmlentities($answer['reply_link']) . '</a>';
                            $op = "<a href='/admin/autoreply/designer/answer/" . $answer['id'] . "/edit' style='text-decoration:underline'>编辑</a>";
                            array_push($answer, $op);
                        }
                        unset($answer);
                        return new Table(['答案ID', '回复内容', '回复类型', '回复链接', '回复顺序', '状态', '操作'], $replyA);
                    }
                }, false);
                $grid->column('admin_name', '最后更新人');
                $grid->column('data_sort', '排序');
                $grid->column('trigger_times', '触发次数');
                $grid->column('data_status', '状态')
                    ->using(AutoReply::STATUS_TXT, $this->data_status)
                    ->dot(self::STATUS_DOT);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();
                    $actions->add(new QuestionDelete);
                    $actions->add(new AnswerAdd);
                });
            }
        );

        $tab = new Tab();
        $tab->add('设计师小助手', $gridList->render());
        $content->row($tab);
        return $content
            ->header('设计师小助手')
            ->description(' ')
            ->breadcrumb(['text' => '自动回复'], ['text' => '设计师小助手']);
    }

    public function formatList(&$list) {
        foreach ($list as &$item) {
            $item['reply_a'] = AutoReply::select(
                ['id', 'reply_title', 'reply_type', 'reply_link', 'data_sort', 'data_status'],
                [
                    'question_id'=>$item['id'],
                    'data_status' => [
                        AutoReply::STATUS_NORMAL,
                        AutoReply::STATUS_HIDDEN
                    ]
                ]
            );
            if ($item['reply_a']) {
                foreach ($item['reply_a'] as &$reply) {
                    $reply['data_status'] = AutoReply::STATUS_TXT[$reply['data_status']];
                    $reply['reply_type'] = AutoReply::REPLY_TYPE_TXT[$reply['reply_type']];
                }
                unset($reply);
            }
            $item['reply_cnt'] = !$item['reply_a'] ? 0 : count($item['reply_a']);
            $item['trigger_times'] = cAutoReply::getTriggerTimes($item['id']) ?? 0;
        }
        unset($item);
    }

    public function edit(Request $request, Content $content, $id = 0) {
        $request = $request->all();
        if (!$id) {
            $isCreate = true;
            $header = '问题新增';
        } else {
            $isCreate = false;
            $header = '问题修改';
        }
        $tab = new Tab();
        $tab->add($header, self::editAction($request, $id, $isCreate));
        return $content->header($header)
            ->breadcrumb(
                [
                    'text' => '自动回复',
                    'url' => route('designer_question.list')
                ],
                ['text' => '设计师小助手'],
                ['text' => $header]
            )->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false) {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = AutoReply::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->text('id', 'ID')->readOnly();
        }

        $form->text('reply_title', '问题')
            ->required();
        $form->text('data_sort', '顺序')
            ->required();
        $form->select('data_status', '状态')
            ->options(AutoReply::STATUS_TXT)
            ->default(AutoReply::STATUS_HIDDEN)
            ->required();
        $form->confirm('确定提交吗？请确认该问题下的回复是否正常哦！');
        $form->action('/admin/autoreply/designer/question/save');
        return $form->render();
    }

    public function save(Request $request) {
        $request = $request->all();
        $data = [
            'reply_title' => $request['reply_title'],
            'data_sort' => $request['data_sort'],
            'admin_uid' => Admin::user()->id,
            'data_status' => $request['data_status']
        ];
        if (isset($request['id'])) {
            // 判断是否有回复，无回复不允许状态设置为显示
            if ($data['data_status'] == AutoReply::STATUS_NORMAL && !AutoReply::get('*', ['question_id' => $request['id'], 'data_status' => AutoReply::STATUS_NORMAL])) {
                $error = new MessageBag(['title' => '该问题下无显示中的问题，无法更新状态为显示']);
                return back()->with(compact('error'));
            }
            $rs = AutoReply::update($data, ['id' => $request['id']]);
        } else {
            if (AutoReply::get('*', [
                'reply_title' => $request['reply_title'],
                'question_id' => 0,
                'data_status' => [
                    AutoReply::STATUS_NORMAL, AutoReply::STATUS_HIDDEN
                ]])) {
                $error = new MessageBag(['title' => '已经存在该问题']);
                return back()->with(compact('error'));
            }
            if ($data['data_status'] == AutoReply::STATUS_NORMAL) {
                $error = new MessageBag(['title' => '新增问题必须隐藏，添加回复后可选择展示']);
                return back()->with(compact('error'));
            }
            $rs = AutoReply::insert($data);
        }
        $title = isset($request['id']) ? '修改成功' : '添加成功';
        if ($rs === false) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/autoreply/designer/question')->with(compact('success'));
    }

}
